using System;
using System.IO;
using System.Security.Cryptography;
using System.Text;

namespace Admin.NET.Application;

public class AesCryptoUtil
{
	private static readonly Encoding encoding = Encoding.UTF8;

	private static readonly PaddingMode padding = PaddingMode.PKCS7;

	private static readonly CipherMode cipher = CipherMode.ECB;

	/// <summary>
	/// 加密
	/// </summary>
	/// <param name="plainTxt">要加密文字</param>
	/// <returns></returns>
	public static string Encrypt(string plainTxt, string aeskey)
	{
		using Aes aes = Aes.Create();
		byte[] key = Encoding.UTF8.GetBytes(aeskey);
		byte[] iv = Encoding.UTF8.GetBytes("1234567891234561");
		aes.Mode = cipher;
		aes.Padding = padding;
		using MemoryStream memoryStream = new MemoryStream();
		using CryptoStream cryptoStream = new CryptoStream(memoryStream, aes.CreateEncryptor(key, iv), CryptoStreamMode.Write);
		byte[] plainBytes = encoding.GetBytes(plainTxt);
		cryptoStream.Write(plainBytes, 0, plainBytes.Length);
		cryptoStream.FlushFinalBlock();
		return Convert.ToHexString(memoryStream.ToArray());
	}

	/// <summary>
	/// 解密
	/// </summary>
	/// <param name="encrypted">密文，</param>
	/// <returns></returns>
	public static string Decrypt(string encrypted, string aeskey)
	{
		using Aes aes = Aes.Create();
		byte[] key = Encoding.UTF8.GetBytes(aeskey);
		byte[] iv = Encoding.UTF8.GetBytes("1234567891234561");
		aes.Mode = cipher;
		aes.Padding = padding;
		using MemoryStream mStream = new MemoryStream(Convert.FromHexString(encrypted));
		using CryptoStream cryptoStream = new CryptoStream(mStream, aes.CreateDecryptor(key, iv), CryptoStreamMode.Read);
		using StreamReader reader = new StreamReader(cryptoStream, encoding);
		return reader.ReadToEnd();
	}
}
